import copy
from utils.string.hex_utils import hex_str_to_bytes
from utils.socket.tcp import ConnectTcpServer
import logging

logger = logging.getLogger()


class LowerComputer(ConnectTcpServer):
    rcv_data_catch = bytearray()

    def send_bytes(self, data):
        """
        若data为str类型：将data解析成bytes再进行发送，如： 'AABBCC' 解析成 b'AABBCC'
        若data为bytes类型：则直接进行数据发送
        """
        if isinstance(data, str):
            send_data = hex_str_to_bytes(data)
        else:
            send_data = data
        self.send(send_data)

    def send_string(self, data):
        send_data = data.encode('utf8')
        self.send(send_data)

    def receive_async(self, data):
        LowerComputer.rcv_data_catch = LowerComputer.rcv_data_catch + data

    def receive_sync(self):
        while True:
            if LowerComputer.rcv_data_catch:
                return_data = copy.deepcopy(LowerComputer.rcv_data_catch)
                LowerComputer.rcv_data_catch.clear()
                return return_data

    def say_hello(self, content):
        data = None
        try:
            self.send_string('hello world')
            self.send_bytes('55AABBFF')
            data = self.receive_sync()
        except Exception as e:
            logger.error(str(e))
        return data

    def sendFrame(self, content):
        data = None
        try:
            self.send_bytes(content['data'])
            data = self.receive_sync()
        except Exception as e:
            logger.error(str(e))
        return data


try:
    lower_computer = LowerComputer('127.0.0.1', 7000)
    lower_computer.connect()
    logger.info("下位机已连接：('127.0.0.1', 7000)")
except Exception as e:
    logger.error('下位机连接失败!!!')
